import { isNil, isString } from 'lodash-es';

export class CustomStorage {
  public storage: Storage;
  constructor(storage = localStorage) {
    this.storage = storage;
  }
  set<T = any>(key: string, value: T) {
    if (isNil(value) || !isString(key)) {
      console.error('setItem error');
      return;
    }
    this.storage.setItem(key, value as unknown as string);
  }
  get<T = any>(key: string, defaultResult = {} as T): T {
    if (!isString(key)) {
      return defaultResult;
    }
    const value = this.storage.getItem(key);
    if (!value) {
      return defaultResult;
    }
    try {
      return JSON.parse(value!) as T;
    } catch (e) {
      return defaultResult;
    }
  }
  remove(key: string) {
    if (!isString(key)) {
      return;
    }
    this.storage.removeItem(key);
  }
  clear() {
    this.storage.clear();
  }
}

export const local = new CustomStorage();
export const session = new CustomStorage(sessionStorage);
